class PasswordGenerator {
    // 字符集定义
    static CHARACTER_SETS = {
        lowercase: 'abcdefghijklmnopqrstuvwxyz',
        uppercase: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
        numbers: '0123456789',
        symbols: '!@#$%^&*()_+-=[]{}|;:,.<>?',
        similarChars: 'il1Lo0O',
        ambiguousChars: '{}[]()/\\\'"`~,;.<>',
    };

    // 预定义密码模板
    static PRESETS = {
        simple: {
            name: '简单密码',
            description: '只含字母和数字，易于记忆',
            length: 12,
            options: {
                includeLowercase: true,
                includeUppercase: true,
                includeNumbers: true,
                includeSymbols: false,
                excludeSimilar: true,
                excludeAmbiguous: true
            }
        },
        standard: {
            name: '标准密码',
            description: '包含字母、数字和符号，安全性较好',
            length: 16,
            options: {
                includeLowercase: true,
                includeUppercase: true,
                includeNumbers: true,
                includeSymbols: true,
                excludeSimilar: true,
                excludeAmbiguous: false
            }
        },
        strong: {
            name: '强密码',
            description: '高安全性密码，适用于重要账户',
            length: 20,
            options: {
                includeLowercase: true,
                includeUppercase: true,
                includeNumbers: true,
                includeSymbols: true,
                excludeSimilar: false,
                excludeAmbiguous: false
            }
        },
        pin: {
            name: '数字PIN',
            description: '纯数字密码，适用于PIN码',
            length: 6,
            options: {
                includeLowercase: false,
                includeUppercase: false,
                includeNumbers: true,
                includeSymbols: false,
                excludeSimilar: true,
                excludeAmbiguous: true
            }
        }
    };

    // 生成随机密码
    static generate(length = 12, options = {}) {
        try {
            const {
                includeLowercase = true,
                includeUppercase = true,
                includeNumbers = true,
                includeSymbols = false,
                excludeSimilar = false,
                excludeAmbiguous = false,
                customChars = '',
                mustIncludeEach = true,
                minNumbers = 1,
                minSymbols = 1,
                minUppercase = 1,
                minLowercase = 1
            } = options;

            if (length < 1 || length > 256) {
                return { success: false, error: '密码长度必须在1-256之间' };
            }

            // 构建字符集
            let charset = '';
            const requiredChars = [];

            if (includeLowercase) {
                let lowerChars = this.CHARACTER_SETS.lowercase;
                if (excludeSimilar) {
                    lowerChars = lowerChars.replace(/[il]/g, '');
                }
                charset += lowerChars;
                if (mustIncludeEach && length >= 4) {
                    requiredChars.push(this.getRandomChar(lowerChars));
                }
            }

            if (includeUppercase) {
                let upperChars = this.CHARACTER_SETS.uppercase;
                if (excludeSimilar) {
                    upperChars = upperChars.replace(/[LO]/g, '');
                }
                charset += upperChars;
                if (mustIncludeEach && length >= 4) {
                    requiredChars.push(this.getRandomChar(upperChars));
                }
            }

            if (includeNumbers) {
                let numberChars = this.CHARACTER_SETS.numbers;
                if (excludeSimilar) {
                    numberChars = numberChars.replace(/[10]/g, '');
                }
                charset += numberChars;
                if (mustIncludeEach && length >= 4) {
                    requiredChars.push(this.getRandomChar(numberChars));
                }
            }

            if (includeSymbols) {
                let symbolChars = this.CHARACTER_SETS.symbols;
                if (excludeAmbiguous) {
                    symbolChars = symbolChars.replace(/[{}[\]()/\\'""`~,;.<>]/g, '');
                }
                charset += symbolChars;
                if (mustIncludeEach && length >= 4) {
                    requiredChars.push(this.getRandomChar(symbolChars));
                }
            }

            if (customChars) {
                charset += customChars;
            }

            if (!charset) {
                return { success: false, error: '至少需要选择一种字符类型' };
            }

            // 生成密码
            const password = this.generatePassword(length, charset, requiredChars);
            
            // 分析密码强度
            const strength = this.analyzeStrength(password);

            return {
                success: true,
                data: {
                    password,
                    strength,
                    charset: charset.length,
                    entropy: Math.log2(Math.pow(charset.length, length)).toFixed(2)
                }
            };

        } catch (error) {
            return { success: false, error: `生成密码失败: ${error.message}` };
        }
    }

    // 生成密码核心逻辑
    static generatePassword(length, charset, requiredChars = []) {
        const array = new Uint8Array(length);
        crypto.getRandomValues(array);
        
        let password = '';
        
        // 首先添加必需的字符
        for (let i = 0; i < requiredChars.length && i < length; i++) {
            password += requiredChars[i];
        }
        
        // 填充剩余长度
        for (let i = requiredChars.length; i < length; i++) {
            const randomIndex = array[i] % charset.length;
            password += charset[randomIndex];
        }
        
        // 打乱字符顺序
        return this.shuffleString(password);
    }

    // 获取随机字符
    static getRandomChar(charset) {
        const array = new Uint8Array(1);
        crypto.getRandomValues(array);
        return charset[array[0] % charset.length];
    }

    // 字符串打乱
    static shuffleString(str) {
        const arr = str.split('');
        const array = new Uint8Array(arr.length);
        crypto.getRandomValues(array);
        
        for (let i = arr.length - 1; i > 0; i--) {
            const j = array[i] % (i + 1);
            [arr[i], arr[j]] = [arr[j], arr[i]];
        }
        
        return arr.join('');
    }

    // 密码强度分析
    static analyzeStrength(password) {
        let score = 0;
        let feedback = [];

        // 长度评分
        if (password.length >= 12) {
            score += 25;
        } else if (password.length >= 8) {
            score += 15;
        } else if (password.length >= 6) {
            score += 10;
        } else {
            feedback.push('密码长度过短');
        }

        // 字符类型评分
        const hasLower = /[a-z]/.test(password);
        const hasUpper = /[A-Z]/.test(password);
        const hasNumber = /[0-9]/.test(password);
        const hasSymbol = /[^a-zA-Z0-9]/.test(password);

        let typeCount = 0;
        if (hasLower) typeCount++;
        if (hasUpper) typeCount++;
        if (hasNumber) typeCount++;
        if (hasSymbol) typeCount++;

        score += typeCount * 10;

        if (typeCount < 3) {
            feedback.push('建议使用多种字符类型');
        }

        // 重复字符检查
        const repeatedChars = password.match(/(.)\1{2,}/g);
        if (repeatedChars) {
            score -= repeatedChars.length * 10;
            feedback.push('存在连续重复字符');
        }

        // 常见模式检查
        if (/123|abc|qwe|asd/i.test(password)) {
            score -= 15;
            feedback.push('包含常见字符序列');
        }

        // 确保得分在0-100范围内
        score = Math.max(0, Math.min(100, score));

        let level, color, description;
        if (score >= 80) {
            level = 'very-strong';
            color = 'text-green-600';
            description = '非常强';
        } else if (score >= 60) {
            level = 'strong';
            color = 'text-blue-600';
            description = '强';
        } else if (score >= 40) {
            level = 'medium';
            color = 'text-yellow-600';
            description = '中等';
        } else if (score >= 20) {
            level = 'weak';
            color = 'text-orange-600';
            description = '弱';
        } else {
            level = 'very-weak';
            color = 'text-red-600';
            description = '非常弱';
        }

        return {
            score,
            level,
            color,
            description,
            feedback
        };
    }

    // 批量生成密码
    static generateBatch(count, length = 12, options = {}) {
        try {
            if (!count || count <= 0) {
                return { success: false, error: '生成数量必须大于0' };
            }

            if (count > 1000) {
                return { success: false, error: '批量生成数量不能超过1000个' };
            }

            const passwords = [];
            const separator = options.separator || '\n';

            for (let i = 0; i < count; i++) {
                const result = this.generate(length, options);
                if (!result.success) {
                    return result;
                }
                passwords.push(result.data.password);
            }

            return {
                success: true,
                data: {
                    passwords,
                    output: passwords.join(separator),
                    count: passwords.length
                }
            };

        } catch (error) {
            return { success: false, error: `批量生成密码失败: ${error.message}` };
        }
    }

    // 检查密码是否被泄露（模拟检查，实际应该使用HaveIBeenPwned API）
    static checkBreached(password) {
        try {
            // 这里只是模拟检查一些常见的弱密码
            const commonPasswords = [
                '123456', 'password', '123456789', '12345678', '12345',
                'qwerty', 'abc123', 'Password', '1234567', 'welcome',
                'login', 'admin', 'root', 'user', 'test', '111111',
                '000000', 'password123', '123123', '1234567890'
            ];

            const isCommon = commonPasswords.includes(password.toLowerCase());
            
            return {
                success: true,
                data: {
                    breached: isCommon,
                    message: isCommon ? '这是一个常见的弱密码，建议更换' : '未发现此密码在常见泄露库中'
                }
            };

        } catch (error) {
            return { success: false, error: `检查密码安全性失败: ${error.message}` };
        }
    }

    // 密码记忆辅助生成（基于词组的密码）
    static generateMemorable(options = {}) {
        try {
            const {
                wordCount = 4,
                separator = '-',
                includeNumbers = true,
                includeSymbols = false,
                capitalizeWords = true
            } = options;

            // 常用词汇库（简化版）
            const words = [
                'apple', 'ocean', 'mountain', 'forest', 'river', 'sunset', 'flower', 'castle',
                'dragon', 'wizard', 'knight', 'magic', 'crystal', 'thunder', 'lightning', 'storm',
                'garden', 'bridge', 'tower', 'star', 'moon', 'sun', 'cloud', 'rainbow',
                'book', 'music', 'dance', 'song', 'story', 'dream', 'hope', 'peace',
                'fire', 'water', 'earth', 'wind', 'snow', 'ice', 'gold', 'silver',
                'red', 'blue', 'green', 'yellow', 'purple', 'orange', 'black', 'white'
            ];

            if (wordCount < 2 || wordCount > 8) {
                return { success: false, error: '词汇数量必须在2-8之间' };
            }

            const selectedWords = [];
            const usedIndices = new Set();

            // 随机选择词汇
            for (let i = 0; i < wordCount; i++) {
                let randomIndex;
                do {
                    const array = new Uint8Array(1);
                    crypto.getRandomValues(array);
                    randomIndex = array[0] % words.length;
                } while (usedIndices.has(randomIndex));

                usedIndices.add(randomIndex);
                let word = words[randomIndex];

                if (capitalizeWords) {
                    word = word.charAt(0).toUpperCase() + word.slice(1);
                }

                selectedWords.push(word);
            }

            let password = selectedWords.join(separator);

            // 添加数字
            if (includeNumbers) {
                const array = new Uint8Array(2);
                crypto.getRandomValues(array);
                const numbers = (array[0] % 90 + 10).toString(); // 10-99
                password += separator + numbers;
            }

            // 添加符号
            if (includeSymbols) {
                const symbols = ['!', '@', '#', '$', '%', '&', '*'];
                const array = new Uint8Array(1);
                crypto.getRandomValues(array);
                const symbol = symbols[array[0] % symbols.length];
                password += symbol;
            }

            // 分析强度
            const strength = this.analyzeStrength(password);

            return {
                success: true,
                data: {
                    password,
                    words: selectedWords,
                    strength
                }
            };

        } catch (error) {
            return { success: false, error: `生成记忆辅助密码失败: ${error.message}` };
        }
    }
}